#!/bin/sh -e

. CI/travis/lib.sh

install_sphinx() {
	$PYTHON --version

	if ! is_python_at_least_ver "$PYTHON" "3.6" ; then
		echo_red "Python version is too old no python interpreter installed"
		return 1
	fi

	command -v $PYTHON
	$PYTHON -m pip install sphinx
	$PYTHON -m pip install sphinx-rtd-theme
}

handle_centos() {
	# FIXME: see about adding `libserialport-dev` from EPEL ; maybe libusb-1.0.0-devel...
	yum -y groupinstall 'Development Tools'

	if is_centos_at_least_ver "8" ; then
		# On CentOS 8, avahi-devel & doxygen are in this repo; enable it
		yum -y install yum-utils
		yum config-manager --set-enabled powertools
		yum -y install python3
		install_sphinx
	else
		yum -y install python3
		install_sphinx
	fi

	# CMake has a bug when installed from repos. Must grab from kitware
	yum -y install wget
	wget https://github.com/Kitware/CMake/releases/download/v3.15.2/cmake-3.15.2.tar.gz
	tar -zxvf cmake-3.15.2.tar.gz
	cd cmake-3.15.2
	./bootstrap
	make
	make install
	cd ..

	# Need libzstd from EPEL
	yum -y install epel-release
	yum -y install libzstd

	yum -y install libxml2-devel libusb1-devel doxygen libaio-devel \
		avahi-devel bzip2 gzip rpm rpm-build

	if [ -n "$PACKAGE_TO_INSTALL" ] ; then
		sudo yum localinstall -y $PACKAGE_TO_INSTALL
	elif [ "$INSTALL_FROM_SW_DOWNLOADS" = "1" ] ; then
		wget http://swdownloads.analog.com/cse/travis_builds/${LIBIIO_BRANCH}_latest_libiio${LDIST}.rpm
		sudo yum localinstall -y ./${LIBIIO_BRANCH}_latest_libiio${LDIST}.rpm
	fi

	$PYTHON -m pip install pylibiio==0.21 --no-binary :all:
}

handle_generic_docker() {
	prepare_docker_image
}

handle_default() {
	sudo apt-get -qq update
	sudo DEBIAN_FRONTEND=noninteractive apt-get install -y cmake doxygen graphviz \
		libaio-dev libavahi-client-dev libavahi-common-dev libusb-1.0-0-dev \
		libxml2-dev rpm tar bzip2 gzip flex bison libserialport-dev \
		python3 python3-pip python3-setuptools

	if [ -n "$PACKAGE_TO_INSTALL" ] ; then
		sudo dpkg -i $PACKAGE_TO_INSTALL
	elif [ "$INSTALL_FROM_SW_DOWNLOADS" = "1" ] ; then
		wget http://swdownloads.analog.com/cse/travis_builds/${LIBIIO_BRANCH}_latest_libiio${LDIST}.deb
		sudo dpkg -i ./${LIBIIO_BRANCH}_latest_libiio${LDIST}.deb
	fi

	$PYTHON -m pip install pylibiio==0.21 --no-binary :all:
	install_sphinx
}

handle_ubuntu() {
	handle_default
}

handle_debian() {
	handle_default
}

setup_build_type_env_vars

handle_${BUILD_TYPE}
